<template>
  <div class="upload-box">
    <el-upload
      action="#"
      :id="uuid"
      :class="['upload', self_disabled ? 'disabled' : '']"
      :multiple="false"
      :disabled="self_disabled"
      :show-file-list="false"
      :http-request="handleHttpUpload"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :accept="props.fileType?.join(',')"
    >
      <template v-if="imageUrl && !loading">
        <img :src="imageUrl" class="upload-image" />
        <div class="upload-handle" @click.stop>
          <div class="handle-icon" @click="editImg" v-if="!self_disabled">
            <el-icon><Edit /></el-icon>
          </div>
          <div class="handle-icon" @click="imgViewVisible = true">
            <el-icon><ZoomIn /></el-icon>
          </div>
          <div class="handle-icon" @click="deleteImg" v-if="!self_disabled">
            <el-icon><Delete /></el-icon>
          </div>
        </div>
      </template>
      <template v-if="!imageUrl && !loading">
        <div class="upload-empty">
          <slot name="empty">
            <svg-icon icon-class="Plus"></svg-icon>
          </slot>
        </div>
      </template>
      <template v-if="!imageUrl && loading">
        <div class="loadings" v-loading="loading"></div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip"></slot>
    </div>
    <el-image-viewer
      v-if="imgViewVisible"
      @close="imgViewVisible = false"
      :url-list="[imageUrl]"
    />
  </div>
</template>

<script setup name="UploadImg">
import { ref, computed, inject } from "vue";
import { uploadImg } from "@/api/index.js";
import { generateUUID } from "@/utils/index.js";
import { formContextKey, formItemContextKey, ElMessage } from "element-plus";

// 接受父组件参数
const props = defineProps({
  imageUrl: {
    type: String,
    default: "",
  },
  fileSize: {
    type: [String, Number],
    default: 5,
  },
  disabled: {
    type: Boolean,
    required: false,
    default: () => {
      return false;
    },
  },
  fileType: {
    type: Array,
    default: () => ["image/jpeg", "image/png", "image/gif", "image/bmp"],
  },
  height: {
    type: String,
    default: "150px",
  },
  width: {
    type: String,
    default: "150px",
  },
  borderRadius: {
    type: String,
    default: "8px",
  },
});

// 生成组件唯一id
const uuid = ref("id-" + generateUUID());
const loading = ref(false);
// 查看图片
const imgViewVisible = ref(false);
// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
  return props.disabled || formContext?.disabled;
});

/**
 * @description 图片上传
 * @param options upload 所有配置项
 * */
const emits = defineEmits([]);
const handleHttpUpload = async (options) => {
  loading.value = true;
  let formData = new FormData();
  const { file } = options;
  formData.append("file", file);
  try {
    const { data } = await uploadImg(formData);
    emits("update:imageUrl", data["data-show-file"]);
    // 调用 el-form 内部的校验方法（可自动校验）
    formItemContext?.prop && formContext?.validateField([formItemContext.prop]);
  } catch (error) {
    options.onError(error);
  }
};

/**
 * @description 删除图片
 * */
const deleteImg = () => {
  emits("update:imageUrl", "");
};

/**
 * @description 编辑图片
 * */
const editImg = () => {
  const dom = document.querySelector(`#${uuid.value} .el-upload__input`);
  dom && dom.dispatchEvent(new MouseEvent("click"));
};

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
const beforeUpload = (rawFile) => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  const imgType = props.fileType.includes(rawFile.type);
  if (!imgType) return ElMessage.error("上传图片不符合所需的格式！");
  if (!imgSize) return ElMessage.error(`上传图片大小不能超过 ${props.fileSize}M！`);
  return imgType && imgSize;
};

/**
 * @description 图片上传成功
 * */
const uploadSuccess = () => {
  loading.value = false;
  // ElMessage.success('上传成功')
};

/**
 * @description 图片上传错误
 * */
const uploadError = () => {
  loading.value = false;
  // ElNotification({
  //   title: '温馨提示',
  //   message: '图片上传失败，请您重新上传！',
  //   type: 'error'
  // })
};
</script>
<style scoped lang="scss">
.is-error {
  .upload {
    :deep(.el-upload),
    :deep(.el-upload-dragger) {
      // border: 1px dashed #3487FF !important;
      &:hover {
        border-color: #3487ff !important;
      }
    }
  }
}
:deep(.disabled) {
  .el-upload,
  .el-upload-dragger {
    cursor: not-allowed !important;
    background: var(--el-disabled-bg-color);
    &:hover {
      border: 1px dashed #3487ff !important;
    }
  }
}
.upload-box {
  .no-border {
    :deep(.el-upload) {
      border: none !important;
    }
  }
  :deep(.upload) {
    .el-upload {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: v-bind(width);
      height: v-bind(height);
      overflow: hidden;
      // border: 1px dashed #3487FF;
      border-radius: v-bind(borderRadius);
      transition: var(--el-transition-duration-fast);
      &:hover {
        border-color: var(--el-color-primary);
        .upload-handle {
          opacity: 1;
        }
      }
      .el-upload-dragger {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        padding: 0;
        overflow: hidden;
        background-color: transparent;
        border: 1px dashed var(--el-border-color-darker);
        border-radius: v-bind(borderRadius);
        &:hover {
          border: 1px dashed var(--el-color-primary);
        }
      }
      .el-upload-dragger.is-dragover {
        background-color: var(--el-color-primary-light-9);
        border: 2px dashed var(--el-color-primary) !important;
      }
      .upload-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      .upload-empty {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        line-height: 30px;
        color: var(--el-color-info);
        border: 1px dashed #3487ff;
        border-radius: 10px;
        width: 100%;
        height: 100%;
        .el-icon {
          font-size: 28px;
        }
      }
      .loadings {
        width: 100%;
        height: 100%;
      }
      .upload-handle {
        position: absolute;
        top: 0;
        right: 0;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        cursor: pointer;
        background: rgb(0 0 0 / 60%);
        opacity: 0;
        transition: var(--el-transition-duration-fast);
        .handle-icon {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 0 6%;
          color: aliceblue;
          .el-icon {
            margin-bottom: 40%;
            font-size: 95%;
            line-height: 130%;
          }
          span {
            font-size: 85%;
            line-height: 85%;
          }
        }
      }
    }
  }
  .el-upload__tip {
    line-height: 18px;
    text-align: center;
  }
}
</style>
